﻿using System;

namespace Gqq.Csharpindepth.Common
{
    /// <summary>
    /// 测试深拷贝和浅拷贝的类（简称拷贝类）
    /// </summary>
    public class CloneTest : ICloneable
    {
        private int _id;
        private string _name;

        public int Id
        {
            get { return _id; }
        }

        public string Name
        {
            get { return _name; }
        }

        public Info Info { get; set; }

        public CloneTest(string name, int id, string adderss)
        {
            _name = name;
            _id = id;
            Info = new Info { Address = adderss };
        }

        public override string ToString()
        {
            return string.Format("Id:{0},Name:{1},Info Address:{2},Info Number:{3},Info Priot:{4}", Id, Name, Info.Address, Info.Number, Info.Priot);
        }

        /// <summary>
        /// 浅拷贝
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            //            throw new NotImplementedException();
            return MemberwiseClone();
        }

        /// <summary>
        /// 深拷贝
        /// </summary>
        /// <returns></returns>
        public object DeepClone()
        {
            CloneTest newO = (CloneTest)MemberwiseClone();
            newO.Info = new Info { Address = Info.Address, Number = Info.Number, Priot = Info.Priot };
            return newO;
        }

        public static void Test()
        {
            CloneTest ct = new CloneTest("yao", 3, "test");
            ct.Info.Priot = 7;
            Console.WriteLine("*************************************************");
            Console.WriteLine("ct is:");
            Console.WriteLine(ct);

            //浅拷贝一个对象
            CloneTest ct2 = (CloneTest)ct.Clone();
            ct2.Info.Address = "test2";
            ct2.Info.Priot = 8;
            Console.WriteLine("*************************************************");
            Console.WriteLine("now ct is");
            Console.WriteLine(ct);

            CloneTest ct3 = (CloneTest)ct.DeepClone();
            ct3.Info.Address = "test3";
            ct3.Info.Priot = 9;
            Console.WriteLine("*************************************************");
            Console.WriteLine("now ct is");
            Console.WriteLine(ct);
            Console.WriteLine("now ct3 is");
            Console.WriteLine(ct3);
        }
    }

    public class Info
    {
        public string Address { get; set; }
        public int Number { get; set; }
        public byte Priot { get; set; }
    }
}
